import config
import os

import re


def path_check(file_path):
    flie_folder = os.path.dirname(os.path.abspath(file_path))
    if not os.path.exists(flie_folder):
        os.makedirs(flie_folder)


def txt_append_line(file_path, line):
    path_check(file_path)
    with open(file_path, 'a+') as f:
        f.write(line + '\n')


def label_file_append(img_path, label):
    txt_append_line(config.LABEL_PATH, str(img_path) + " " + str(label))

def natural_key(string_):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [
        int(s) if s.isdigit() else s
        for s in re.split(r'(\d+)', string_.lower())
    ]


def load_class_map(filename, root=''):
    """将离散的类标签转化为对应的标签字典

    Args:
        filename (str): 文件名
        root (str, optional): 可以指定文件路径. Defaults to ''.

    Returns:
        dict: 类别对应的标签字典
    """
    class_map_path = filename
    if not os.path.exists(class_map_path):
        class_map_path = os.path.join(root, filename)
        assert os.path.exists(
            class_map_path
        ), 'Cannot locate specified class map file (%s)' % filename
    class_map_ext = os.path.splitext(filename)[-1].lower()
    if class_map_ext == '.txt':
        with open(class_map_path) as f:
            class_to_idx = {v.strip(): k for k, v in enumerate(f)}
    else:
        assert False, 'Unsupported class map extension'
    return class_to_idx
